package com.unicom.priceboard.thread;

import java.io.File;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import com.unicom.priceboard.data.hose.TotalMarketReader;
import com.unicom.priceboard.data.vo.HoIndex;
import com.unicom.priceboard.data.vo.TotalMarketElement;
import com.unicom.priceboard.util.Constants;
import com.unicom.priceboard.util.DataPath;
import com.unicom.priceboard.util.MarketStateUtil;
import com.unicom.priceboard.util.NumberUtil;
import com.unicom.priceboard.util.ReadFileUtil;
import com.unicom.priceboard.util.Util;

public class TotalMarketThread implements Runnable{
	
	public static HashMap<Integer,TotalMarketElement> mapTotalMarket=new HashMap<Integer,TotalMarketElement>();
	private static TotalMarketElement currentTotalMarket = new TotalMarketElement();
	private int wait = 60; //seconds
	
	private static String totalMarketSrcPath = "";
	private static String securityPath = "";
	private static String sessionPath = "";
	
	private int curday=-1;
	private int reset=-1;
	
	
	public TotalMarketThread()	{
		totalMarketSrcPath = DataPath.basePath + DataPath.totalMarketSrcPath;
		securityPath = DataPath.basePath + DataPath.securityPath;
		sessionPath = DataPath.sessionPath;
		this.wait=Integer.parseInt(DataPath.hoseWait);
	}
	private TotalMarketReader readFile = new TotalMarketReader();
	public void run() {
		
		while(true)	{
			try{
				//reset data for new day				
				curday=TimerThread.CURRENT_DAY_OF_WEEK;
				if(reset!=curday){
					if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(securityPath))){
						resetData_Totalmarket();
						reset=curday;//check for read file once Time a day
					}
				}				
				if(TimerThread.CURRENT_DAY_OF_WEEK!=1 && TimerThread.CURRENT_DAY_OF_WEEK!=7){
					if(TimerThread.CURRENT_TIME>=Constants.READING_TIME_START && TimerThread.CURRENT_TIME<Constants.READING_TIME_END)	{
						if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(totalMarketSrcPath))){							
							
							readFile.Totalmarket(totalMarketSrcPath);
//							System.out.println("---reading here: 1 -> src: " + totalMarketSrcPath);
						  } else if (mapTotalMarket.size()==0) {
							  readFile.Totalmarket(totalMarketSrcPath);
						  }//end last modify						
					}else if(mapTotalMarket.size()==0) {
						if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(totalMarketSrcPath))){
							readFile.Totalmarket(totalMarketSrcPath);
//							System.out.println("---reading here: 2 -> src: " + totalMarketSrcPath);
						}
					}
				}else if(mapTotalMarket.size()==0) {
					readFile.Totalmarket(totalMarketSrcPath);
//					System.out.println("---reading here: 3 -> src: " + totalMarketSrcPath);
				}
			}catch(Exception e)	{
				e.printStackTrace();
				//System.out.println("exception o day roi: " + e);
			}
			try {
				//logger.debug("***** parsing TOTALMKT.DAT Wait for " + wait + " seconds");
				Thread.sleep(1000*wait);
			} catch (Exception e) {
				//logger.debug("Exception: " + e.getMessage());
			}			
		}
	}
	
	private void resetData_Totalmarket(){
		TotalMarketReader.prev=0;
		TotalMarketReader.idxBegin_T4=0;
		TotalMarketReader.idxBegin_T3=0;
		TotalMarketReader.idxBegin_T2=0;		
		mapTotalMarket.clear();
		int new_Session=Integer.valueOf(ReadFileUtil.readSessionFile(sessionPath));
		ReadFileUtil.writeSessionFile(String.valueOf(new_Session+1),sessionPath);		
	}
	/**
	 * 
	 * @param session
	 * @return
	 */
	public static HoIndex getIndex(int session) {
		TotalMarketElement indexUpdate = mapTotalMarket.get(session);
		// HashMap<String,String>temp =new HashMap<String, String>();
		HoIndex hcmIndex = new HoIndex(); // create new instant
		String today;
		/*
		 * nguyen sua cho nay => luu market track DateFormat dateFormat = new
		 * SimpleDateFormat("dd/MM/yyyy");
		 */
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

		File curFileTrading = new File(Util
				.getCurrentDataPath(totalMarketSrcPath));
		File preFileTrading = new File(sessionPath);
		// ReadFileUtil sessiontext= new ReadFileUtil(sessionPath);
		// ReadFileUtil curday=new
		// ReadFileUtil(Util.getCurrentDataPath(totalMarketSrcPath));
		if (ReadFileUtil
				.isUpToDate(Util.getCurrentDataPath(totalMarketSrcPath))) {
			today = dateFormat.format(new Date(curFileTrading.lastModified()));
		} else {
			today = dateFormat.format(new Date(preFileTrading.lastModified()));
		}
		if (indexUpdate != null) {
			if (indexUpdate.getSetIndex() % 100 > 0)
				hcmIndex.setVnIndex(String.valueOf(((double) indexUpdate
						.getSetIndex() / 100)));
			else
				hcmIndex.setVnIndex(String
						.valueOf((indexUpdate.getSetIndex() / 100)));
			double prevIndex;
			double change = 0;
			double changed = 0;
			int setIndex = 0;
			prevIndex = (double) TotalMarketReader.prev / 100;
			setIndex = indexUpdate.getSetIndex();
			if (setIndex != 0) {
				change = (((double) setIndex / 100) - prevIndex);
				changed = ((((double) setIndex / 100) - prevIndex) / prevIndex) * 100;
			}
			DecimalFormat df = new DecimalFormat("#.##");

			hcmIndex.setChange(df.format(change));
			hcmIndex.setChangePer(df.format(changed));
			hcmIndex.setTotalTrade(String.valueOf(NumberUtil
					.formatLong(indexUpdate.getTotalTrade())));
			hcmIndex.setTotalShares(NumberUtil.formatNumber(indexUpdate
					.getTotalShare()));
			hcmIndex.setTotalValue(NumberUtil.formatNumber(indexUpdate
					.getTotalValue() * 1000000));
			hcmIndex.setVnIndex_date(today);
			hcmIndex.setSession(ReadFileUtil.readSessionFile(sessionPath));
			hcmIndex.setIdSession(session);
			hcmIndex.setMarketState(MarketStateUtil.getHoseState());
			// end if
		} else {
			// HCMIndex.setCenterId("0");
			hcmIndex.setChange("0");
			hcmIndex.setChangePer("0.0");
			hcmIndex.setTotalShares("0");
			hcmIndex.setTotalValue("0");
			hcmIndex.setVnIndex("0");
			hcmIndex.setTotalTrade("0");
			hcmIndex.setVnIndex_date(today);
			hcmIndex.setIdSession(session);
			hcmIndex.setMarketState(MarketStateUtil.getHoseState());
			hcmIndex.setSession(ReadFileUtil.readSessionFile(sessionPath));
		}
		return hcmIndex;
	}

	public static HoIndex getCurrentIndex() {
		HoIndex hoseIndex = new HoIndex();
		String today;
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		File curFileTrading = new File(Util
				.getCurrentDataPath(totalMarketSrcPath));
		File preFileTrading = new File(sessionPath);
		if (ReadFileUtil.isUpToDate(Util.getCurrentDataPath(totalMarketSrcPath))) {
			today = dateFormat.format(new Date(curFileTrading.lastModified()));
		} else {
			today = dateFormat.format(new Date(preFileTrading.lastModified()));
		}
		if (currentTotalMarket != null) {
			Integer index = currentTotalMarket.getSetIndex();
			if (null != index) {
				if (index % 100 > 0) {
					hoseIndex.setVnIndex(String.valueOf(((double)index / 100)));
				} else {
					hoseIndex.setVnIndex(String
							.valueOf((index / 100)));
				}
			}
			double prevIndex;
			double change = 0;
			double changePercent = 0;
			int setIndex = 0;
			prevIndex = (double) TotalMarketReader.prev / 100;
			if (null != currentTotalMarket.getSetIndex()) {
				setIndex = currentTotalMarket.getSetIndex();
			}
			if (setIndex != 0) {
				change = (((double) setIndex / 100) - prevIndex);
				if (prevIndex != 0) {
					changePercent = ((((double) setIndex / 100) - prevIndex) / prevIndex) * 100;
				}
			}
			DecimalFormat df = new DecimalFormat("#.##");

			hoseIndex.setChange(df.format(change));
			hoseIndex.setChangePer(df.format(changePercent));
			hoseIndex.setTotalTrade(String.valueOf(NumberUtil
					.formatLong(null != currentTotalMarket.getTotalTrade() ? currentTotalMarket.getTotalTrade() : 0)));
			hoseIndex.setTotalShares(NumberUtil.formatNumber(null != currentTotalMarket.getTotalShare() ? currentTotalMarket.getTotalShare() : 0));
			if (null != currentTotalMarket.getTotalValue() && currentTotalMarket.getTotalValue() > 0) {
				hoseIndex.setTotalValue(NumberUtil.formatNumber(currentTotalMarket.getTotalValue() * 1000000));
			} else {
				hoseIndex.setTotalValue("0.0");
			}
			hoseIndex.setVnIndex_date(today);
			hoseIndex.setSession(ReadFileUtil.readSessionFile(sessionPath));
			hoseIndex.setMarketState(MarketStateUtil.getHoseState());
			// end if
		} else {
			// HCMIndex.setCenterId("0");
			hoseIndex.setChange("0");
			hoseIndex.setChangePer("0.0");
			hoseIndex.setTotalShares("0");
			hoseIndex.setTotalValue("0");
			hoseIndex.setVnIndex("0");
			hoseIndex.setTotalTrade("0");
			hoseIndex.setVnIndex_date(today);
			hoseIndex.setMarketState(MarketStateUtil.getHoseState());
			hoseIndex.setSession(ReadFileUtil.readSessionFile(sessionPath));
		}
		return hoseIndex;
	}

	public static TotalMarketElement getCurrentTotalMarket() {
		return currentTotalMarket;
	}
	
	public static void setCurrentTotalMarket(TotalMarketElement element) {
		currentTotalMarket = element;
	}
}